using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PSE.Deployment.SetupBase.Parameter.Enums;

namespace PSE.Deployment.SetupBase.Commands
{
    public class RepairCommand : ICommand
    {
        private const string HideWizardOption = "/hidewizard";
        private const string HideResultOption = "/hideresult";

        private bool ValidateArguments(string[] args, out string[] returnArgs)
        {
            bool isvalid = true;
            returnArgs = null;

            bool showWizard = true;
            bool showResult = true;
            string filename = String.Empty;

            for (int i = 1; i < args.Length; i++)
            {
                string[] arg;

                if (args[i].StartsWith("/"))
                {
                    arg = args[i].Split(':');

                    if (arg.Length == 1)
                    {
                        switch (arg[0].Trim().ToLower())
                        {
                            case HideWizardOption:
                                showWizard = false;
                                break;
                            case HideResultOption:
                                showResult = false;
                                break;
                        }
                    }
                }
            }

            returnArgs = new string[] { showWizard.ToString(), showResult.ToString() };

            return isvalid;
        }

        #region ICommand Members

        public int Execute(string[] args)
        {
            string[] returnArgs;
            int executed = 0;

            if (ValidateArguments(args, out returnArgs))
            {
                string showWizard = returnArgs[0];
                string showResult = returnArgs[1];

                try
                {
                    if (SetupMainFactory.GetInstance().Parameter.IsInstalled)
                    {
                        SetupMainFactory.GetInstance().Parameter.SetupMode = SetupMode.Repair;
                        SetupMainFactory.GetInstance().Parameter.ShowWizard = Convert.ToBoolean(showWizard);
                        SetupMainFactory.GetInstance().Parameter.ShowResult = Convert.ToBoolean(showResult);

                        SetupApplication application = new SetupApplication();
                        application.CheckCurrentProcess = false;
                        executed = application.Run();
                    }
                    else
                        Messages.SystemNotInstalled();
                }
                catch (Exception ex)
                {
                    executed = -1;
                    Messages.WriteFailMessage(ex);
                }
            }

            return executed;
        }

        #endregion
    }
}